'use strict';

// 工具函数
const Tool = {
    html(str) {
        var s = '';
        if (str.length == 0) return '';
        s = str.replace(/&lt;/g, "<");
        s = s.replace(/&gt;/g, ">");
        s = s.replace(/&#39;/g, "'");
        s = s.replace(/&quot;/g, "\"");
        s = s.replace(/&amp;/g, "&");
        return s;
    }
}

class CardEditor {
    constructor(id, updateCallback) {
        var _self = this // 用于闭包变量
        this.name = "card_editor"
        this.editor = this.id(id)
        this.content = "" // 文本内容
        this.code = 0 // 判断是否显示源码
        this.initModule()

        // 使用 iframe 作为主体
        this.iframe = this.c('iframe')
        this.iframe.id = this.iframeId
        this.iframe.frameBoard = 0
        this.editor.appendChild(this.iframe)

        this.window = this.iframe.contentWindow
        this.document = this.iframe.contentDocument
        this.document.body.designMode = "on"
        this.document.contentEditable = true // 设置 document 内容可编辑

        // 文本内容
        this.content = this.document.body
            // 更新文本后进行回调
        this.updateCallback = updateCallback

        // 监听文本变化
        if (this.textarea) {
            setInterval(function() {
                _self.setTextarea()
            }, 1000)
        }

        this.inputEnable()

        this.initParam()
        this.registerListener()
    }

    // 转处理函数
    id(id) {
        return document.getElementById(id)
    }

    c(label) {
        return document.createElement(label)
    }

    getHTML() {
        return this.content.innerHTML
    }

    // 设置功能模块 id， 用于遍历监听功能状态
    initModule() {
        this.iframeId = "_iframe" + this.getTime;
    }

    // 初始化参数
    initParam() {
        this.range = this.document.createRange ? this.window.getSelection() : this.document.selection.crearteRagne()
    }

    setTextarea() {
        if (!this.textarea) return;
        let html = this.code ? Tool.html(this.getHTML()) : this.getHTML()
        html = html.replace(/<pre(.*?)>(.*?)<\/pre>/gi, function(all, a = '', b = '') {
            return '<pre' + a + '>' + b.split('<br>').join("\n") + '</pre>';
        });
        this.textarea.value = html;
    }

    // 注册监听者
    registerListener() {
        const _self = this

        // 处理文本输入
        this.document.body.addEventListener('keydown', function(e) {
            // const selection = _self.range.getRangeAt(0)
            if (e.keyCode == 13) { // 回车
            }

            const html = _self.getHTML()
            _self.updateCallback(html)
        })

    }

    // 控制输入
    inputEnable() {
        this.document.body.designMode = 'on'
        this.document.body.contentEditable = true
    }
    inputDisable() {
        this.document.body.designMode = 'off'
        this.document.body.contentEditable = false
    }

    // 显示隐藏
    hide() {
        this.iframe.style.display = "none"
    }
    show() {
        this.iframe.style.display = "block"
    }
}

export default CardEditor